import React, { useEffect, useState } from 'react'
import style from './recharge.module.css'
import { Button, DatePicker, Form, Table, Modal,Input, InputNumber, Radio, Select} from 'antd';
import moment from 'moment';
import type { TableProps } from 'antd';
import { getGuoTableData } from '../../request';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
// 表格数据类型
interface DataType {
  key: string;
  name: string;
  shopname: string;
  phone: number;
  bill: string;
  types: string;
  watertypes: string;
  time: string;
  money: string;
  password: string;
}
const columns: TableProps<DataType>['columns'] = [
  {
    title: '序号',
    dataIndex: 'key',
    key: 'key'
  },
  {
    title: '用户名',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '店铺名称',
    dataIndex: 'shopname',
    key: 'shopname',
  },
  {
    title: '手机号码',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '业务单据',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '业务类型',
    dataIndex: 'types',
    key: 'types',
  },
  {
    title: '流水类型',
    dataIndex: 'watertypes',
    key: 'watertypes',
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
  },
  {
    title: '果币(元)',
    dataIndex: 'money',
    key: 'money',
    render: money => <span style={{ color: '#f00' }}>{money}</span>
  },
];
function Index() {
  // 禁用表单
  //  const [componentDisabled, setComponentDisabled] = useState<boolean>(true);
  // 获取表格数据
  const [tableData, setTableData] = useState<DataType>([])
  const [filterData, setFilterData] = useState<DataType>([])
  const [businessTypes, setBusinessTypes] = useState<string | undefined>()
  const [shopName, setShopName] = useState<string>('')
  const [phone, setPhone] = useState<string>('')
  useEffect(() => {
    getGuoTableData().then((res) => {
      setTableData(res.data.tab)
      console.log(res.data.tab)
      // 搜索
      setFilterData(res.data.tab)
    })

  }, [])
  // 设置默认日期范围
  const initialDateRange = [moment('2003-12-10', 'YYYY-MM-DD'), moment('2006-6-15')]
  // 果币充值弹框
  const [open, setOpen] = React.useState<boolean>(false);
  const [loading, setLoading] = React.useState<boolean>(true);
  // 新增
  const [openx, setOpenx] = React.useState<boolean>(false);
  const [loadingx, setLoadingx] = React.useState<boolean>(true);

  const showLoading = () => {
    setOpen(true);
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 2000);
  };

  const showLoadingx = () => {
    setOpenx(true);
    setLoadingx(true);
    setTimeout(() => {
      setLoadingx(false);
    }, 2000);
  };
  // 搜索函数
  const handleSearch = () => {
     const filteredData = tableData.filter(item => {
       const newBusinessType = businessTypes? item.types === businessTypes : true;
       const newShopName = shopName? item.shopname.includes(shopName) : true;
       const newPhone = phone? item.phone.toString().includes(phone) : true;
       return newBusinessType && newShopName && newPhone;
     });
     setFilterData(filteredData);
   };
  // 导出
  const handleExport = () => {
    const csvData = filterData.map(item => ({
      '序号': item.key,
      '用户名': item.name,
      '店铺名称': item.shopname,
      '手机号码': item.phone,
      '业务单据': item.bill,
      '业务类型': item.types,
      '流水类型': item.watertypes,
      '时间': item.time,
      '果币(元)': item.money,
    }))

    // 将数据转成CSV格式
    const csvRows = []
    const headers = Object.keys(csvData[0])
    csvRows.push(headers.join(','))//添加表头
    for (const row of csvData) {
      csvRows.push(headers.map(field => JSON.stringify(row[field])).join(','))//添加每一行数据
    }
    // 创建一个 Blob 对象并生成下载链接
    const csvString = csvRows.join('\n');
    const blob = new Blob([csvString], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.setAttribute('hidden', '');
    a.setAttribute('href', url);
    a.setAttribute('download', 'export.csv');
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  // 新增
  const [xinRecord, setXinRecord] = useState<Partial<DataType>>({})
  // 添加记录
  const handleAdd = () => {
    const newRecordData: DataType = {
      key: String(tableData.length + 1),
      name: xinRecord.name || '',
      shopname: xinRecord.shopname || '',
      phone: Number(xinRecord.phone) || 0,
      bill: xinRecord.bill || '',
      types: xinRecord.types || '',
      watertypes: xinRecord.watertypes || '',
      time: xinRecord.time || moment().format('YYYY-MM-DD'),
      money: String(xinRecord.money) || '0',
      password: xinRecord.password || '',
    };
    setTableData([...tableData, newRecordData]);
    setFilterData([...filterData, newRecordData]);
    setOpenx(false);
    setXinRecord({});
  };
  return (
    <div className={style.guomain}>

      <div className={style.guo_top}>
        <h3>果币</h3>
        <div className={style.guo_topbody}>
          <Select
            defaultValue="业务类型"
            style={{ width: 120 }}
            onChange={setBusinessTypes}
          >
            <Select.Option value=''>全部</Select.Option>
            <Select.Option value='充值'>充值</Select.Option>
            <Select.Option value='订单消费'>订单消费</Select.Option>
            <Select.Option value='退款'>退款</Select.Option>
          </Select>
          <div>
            <span>店铺名称</span>
            <input placeholder="请输入店铺名称" onChange={(e) => setShopName(e.target.value)} />
          </div>
          <div>
            <span>手机号</span>
            <input placeholder="请输入手机号" onChange={(e) => setPhone(e.target.value)} />
          </div>
        </div>
        <div className={style.guo_topbody1}>
          <Form initialValues={{ RangePicker: initialDateRange }}>
            <Form.Item
              label="日期查询"
              name="RangePicker"
              rules={[{ required: false, message: 'Please input!' }]}
            >
              <RangePicker />
            </Form.Item>
          </Form>
          <Button style={{ width: '80px' }} type='primary' onClick={handleSearch}>查询</Button>
          <Button style={{ width: '80px' }} onClick={handleExport}>导出</Button>
        </div>
      </div>
      <div className={style.guo_body}>
        <Button style={{ width: '80px' }} type='primary' onClick={showLoading}>充值</Button>&nbsp;
        <Button type="primary" onClick={showLoadingx}>
          新增
        </Button>
        <Table columns={columns} dataSource={filterData} />
      </div>
      {/* 果币充值弹框 */}
      <Modal
        title={<p>果币充值</p>}
        footer={
          <div style={{ marginRight: '130px' }}>
            <Button type="primary" >
              确定充值
            </Button>
            <Button style={{ width: '90px', marginLeft: '20px' }} onClick={() => setOpen(false)}>
              取消
            </Button>
          </div>

        }
        loading={loading}
        open={open}
        onCancel={() => setOpen(false)}
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          // disabled={componentDisabled}
          style={{ maxWidth: 600 }}
        >
          <Form.Item label="充值类型">
            <Radio.Group onChange={(e) => setXinRecord({ ...xinRecord, types: e.target.value })}>
              <Radio value="平台果市"> 平台果市 </Radio>
              <Radio value="店铺果市"> 店铺果市 </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="手机号">
            <TextArea rows={4} onChange={(e) => setXinRecord({ ...xinRecord, phone: e.target.value })} />
          </Form.Item>
          <Form.Item label="充值金额">
            <InputNumber onChange={(e) => setXinRecord({ ...xinRecord, money: e.target.value })} />元
          </Form.Item>
          <Form.Item label="赠送金额">
            <InputNumber onChange={(e) => setXinRecord({ ...xinRecord, money: e.target.value })} />元
          </Form.Item>
          <Form.Item<DataType>
            label="管理员密码"
            name="password"
            rules={[{ required: false, message: '请输入管理员密码!' }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>

      </Modal>
      {/* 新增弹框 */}
      <Modal
        title="添加新记录"
        visible={openx}
        onCancel={() => setOpenx(false)}
        footer={[
          <Button key="cancel" onClick={() => setOpenx(false)}>取消</Button>,
          <Button key="submit" type="primary" onClick={handleAdd}>确认</Button>,
        ]}
        loading={loadingx}
      >
        <Form layout="vertical">
          <Form.Item label="用户名">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, name: e.target.value })} />
          </Form.Item>
          <Form.Item label="店铺名称">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, shopname: e.target.value })} />
          </Form.Item>
          <Form.Item label="手机号">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, phone: e.target.value })} />
          </Form.Item>
          <Form.Item label="业务单据">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, bill: e.target.value })} />
          </Form.Item>
          <Form.Item label="业务类型">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, types: e.target.value })} />
          </Form.Item>
          <Form.Item label="流水类型">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, watertypes: e.target.value })} />
          </Form.Item>
          <Form.Item label="时间">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, time: e.target.value })} />
          </Form.Item>
          <Form.Item label="果币(元)">
            <Input onChange={(e) => setXinRecord({ ...xinRecord, money: e.target.value })} />
          </Form.Item>
          <Form.Item label="管理员密码">
            <Input.Password onChange={(e) => setXinRecord({ ...xinRecord, password: e.target.value })} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index
